'''
    @project: Masdevallia
    @author: Austin Baker
    @created: 2/22/2014
    @license: http://opensource.org/licenses/mit-license.php

    The MIT License (MIT)

    Copyright (c) 2014 Austin Baker
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    
    About:
    A class used to manipulate Maya nodes. Initialize by passing it a string
    representing the name of an object in the active scene. Once created this class
    can be used to access Maya's DAG system.    
'''

'''
============================================================
--->>   IMPORT MODULES
============================================================
'''
import maya.OpenMaya as OM
import masdevallia.utility.Dag as Dag
import masdevallia.utility.Matrix as Matrix

'''
============================================================
--->>   NODE CLASS
============================================================
'''
class Node( object ):
    '''
    Creates a Node class for the passed in string. This string is the name of an
    object in Maya.
    @inObjName: String or MObject. If string then name of object.
    '''
    
    '''
    def __new__( cls, inObj ):
        if isinstance( inObj, str ) and Dag.objExists( inObj ):
            return super( Node, cls ).__new__( cls, inObj )
        elif isinstance( inObj, OM.MObject ):
            return super( Node, cls ).__new__( cls, inObj )
        else:
            raise RuntimeError( 'inObj is not a string. {0}'.format( type( inObj ) ) )
    '''
        
    def __init__( self, *args ):
        if len( args ) == 1 and isinstance( args[0], str ) or isinstance( args[0], OM.MObject ):
            self.name = Dag.getPathname( args[0], inFull=False )
            self.fullName = Dag.getPathname( args[0], inFull=True )
            
            # DO THIS STUFF
            self.parent = None
            self.children = None
            self.shapes = None
            
            
        elif len( args ) != 1:
            #sys.stderr.write
            OM.MGlobal.displayError( '{0} arguments passed. Class takes exactly one'.format( len( args ) ) )
        else:
            OM.MGlobal.displayError( 'Argument passed in is of type {0}. Needs to be string.'.format( type( args[0] ) ) )
    
    def asMObject( self ):
        '''
        Gets the Node as a MObject.
        @return: MObject.
        '''
        return Dag.getMObject( self.name )
    
    def asDagPath( self ):
        '''
        Get the Node as a MDagPath.
        @return: MDagPath.
        '''
        return Dag.getDagPath( self.name )
    
    def getMatrixData( self, inMatrixType='matrix' ):
        '''
        Get matrix of the given type for this Node.
        @return: MMatrix.
        '''
        #print 'getMatrixData: {0}'.format( self.fullName )
        return Matrix.Matrix( self.fullName, inMatrixType )
    
    def getParent( self ):
        '''
        Get the parent of this Node.
        @return: Node. Parent.
        '''
        dagFn = OM.MFnDagNode( self.asDagPath() )
        return Node( dagFn.parent(0) )
    
    def getAllParents( self ):
        '''
        Get all the parents of this Node. In some situations transform and shape
        nodes can have multiple parent nodes - these nodes are instanced. Read more
        about this in the Maya API Guide > DAG Hierarchy > Nodes section.
        @return: List of MObjects.
        '''
        parentList = []
        dagFn = OM.MFnDagNode( self.asDagPath() )
        for idx in xrange( dagFn.parentCount() ):
            parentList.append( dagFn.parent( idx ) )
        return parentList
    
    def setParent( self, inParent ):
        '''
        Reparent this Node to the given new parent.
        @inParent: MObject. New parent for this Node.
        '''        
        dagMod = OM.MDagModifier()
        print self.asMObject()
        print inParent
        dagMod.reparentNode( self.asMObject(), inParent )
        dagMod.doIt()
            
    def getChildren( self, inType=OM.MFn.kTransform ):
        '''
        Get all the children of this Node. Defaults to kTransform type.
        @inType: MFn::Type. See Maya documentation for a list of all types.
        @return: List of MObjects. Empty list if there are no children.
        '''
        childList = []
        dagFn = OM.MFnDagNode( self.asDagPath() )
        childCount = dagFn.childCount()
        if childCount > 0:
            for idx in range( childCount ):
                child = dagFn.child( idx )
                if child.apiType() == inType:
                    childList.append( child )
        return childList
    
    def setChildren( self, inChildren ):
        '''
        Adds the given object(s) to this Node as children.
        @inChildren: String or List. Children to add to this Node.
        '''
        Dag.doReparent( inChildren, self.asMObject(), keepTransform=True )